<?php
require_once("inc.member.php");

$this_title=__("Update Stockist Code");
$page_title=__("Update Stockist Code");
$list_file=$vars["file"]["member"]["stockist_plan"];

if(!$get_s["id"]){
  $errmsg=__("No stockist with that ID found!");
}elseif(!@mysql_num_rows($r=mysql_query("select * from $db->users where id='$get_d[id]'"))){
  $errmsg=__("No stockist with that ID found!");
}else{
  $r_user=mysql_fetch_assoc($r);
}

if($errmsg){
 $errmsg="<h2>$page_title</h2>".format_err($errmsg);

 print format_member_page($errmsg, $this_title, $content_title);
 exit();
}

$td_width=180;
$datetime=ndate($vars["system_date_format"]);

//#####AJAX CALL#####
if($_GET["aj"] && $_GET["check_stockist_code"]){
 if($r_ref=get_stockist_detail_by_stockist_code($post_d['stockist_code'], $_GET['id'])){
  $ajerrmsg=replace_tag(__("Stockist code '<%code%>' already exist."), array("<%code%>"=>$post_d['stockist_code']));
 }else{
  $ajmsg=replace_tag(__("Stockist code <%code%> available."), array("<%code%>"=>$post_d['stockist_code']));
 }
 $xml=array("status"=>($ajerrmsg? "2" : "1"), "msg"=>$ajmsg.$ajerrmsg);
 print format_xml($xml);
 exit();
}
//#####END AJAX CALL#####

//#####EDIT STOCKIST CODE POST#####
if($_POST["__req"]){
 //#####ERROR CHECK#####
 $chk_arr="stockist_code";
 $chk_arrr=explode(",", $chk_arr);
 foreach($post_s as $f=>$v){
  if(in_array($f, $chk_arrr)){
   $data[$f]=$v;
  }
 }
 $errmsg=verify_form_data("users", $data);
 if(!$errmsg){
  //check stockist_code
  if(strlen($post_s['stockist_code'])){
   if($r_ref=get_stockist_detail_by_stockist_code($post_d["stockist_code"], $_GET['id'])){
    $errmsg.=replace_tag(__("Stockist code: '<%code%>' already exist."), array("<%code%>"=>$post_d["stockist_code"]))."<br />\n";
   }
  }	
 }
 //#####END ERROR CHECK#####

 //#####UPDATE TO DB#####
 if(!$errmsg){  
   //field formatting
   $field_arr=explode(",", $chk_arr);
   for($i=0,$t=count($field_arr);$i<$t;$i++){
    $uq.=($uq? ", " : "").(substr($field_arr[$i], 0, 1) == '_'? substr($field_arr[$i], 1) : $field_arr[$i])."='".$post_d[$field_arr[$i]]."'";
   }
   $sql="update $db->users set stockist_code='$post_d[stockist_code]' where id='$get_d[id]' limit 1";
   if(!mysql_query($sql)){
    $errmsg.=__("Error updating the stockist record.")."<br />\n<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n";
   }
   if(!$errmsg){
    $msg=__("The stockist record has been successfully updated.")."<br />\n";
    $r_user=mysql_fetch_assoc(mysql_query("select * from $db->users where id='$get_d[id]'"));
   }
  }

 $msg=$msg? format_msg($msg) : "";
 $errmsg=$errmsg? format_err(__("There is some error(s), please correct them before continuing:")."<br />\n<br />\n$errmsg") : "";
}
//#####END STOCKIST POST#####

$form_fields=array("id"=>"","name"=>"","username"=>"","stockist_uid"=>"","stockist_code"=>"");
foreach($form_fields as $field => $default){
 $db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;
 $dis[$field]=(!$post_s["__req"]? ($_GET["type"]=="edit"? nhtmlentities($r_user[$db_fieldname]) : $default) : $post_h[$field]);
}
/*
//stockist_code
if($dis["_stockist_code"]){
 if($r=get_stockist_detail_by_stockist_code($dis["_stockist_code"], $dis["_id"])){
  $stockist_code_text="<span class='red'>".__("Stockist code already exist")."</span>";
 }else{
  $stockist_code_text="<span class='bold'>".__("Without stockist code member will unable to select")."</span>";
 }
}
*/
//javascript
$jvscript=
"<script type='text/javascript' src='".JS_URL."/get_file_gzip.php?file=".urlencode("common.js,jquery.js")."'></script>
<script type='text/javascript'>
jQuery(document).ready(function(j){
 j('form[@name=user_form]').submit(function(){
  j('input[@name=submit_btn]').attr('disabled','disabled');
 });

 j('input#check_stockist_code_btn').click(function(){
  j('span#aid_text').html('').removeClass('red');
  if(j('input[@name=stockist_code]').val()==''){
   j('span#stockist_code_text').html('".AddSlashes(__("Please provide a Stockist Code!"))."').addClass('red');
  }else{
   j(this).attr('disabled','disabled');
   j.ajax({
    url: '$this_file?aj=1&type=$get_s[type]".($get_s["type"]=="edit"? "&id=$get_s[id]" : "")."&check_stockist_code=1',
    data: {'stockist_code': j('input[@name=stockist_code]').val()},
    type: 'post',
    dataType: 'xml',
    error: function(){
     j('span#stockist_code_text').html('".AddSlashes(__("Error checking..."))."').addClass('red');
    },
    success: function(data){
     var mesg='';
     if(j('loggedout', data).text()=='loggedout'){
      mesg='".AddSlashes(__("You have been logged out."))."';
     }else{
      j(data).find('msg').each(function(){
       mesg+=j(this).text()+' ';
      });
     }
     var status=j(data).find('status').text();
     j('span#stockist_code_text').html(mesg).addClass(status==1? 'bold' : 'red');
    },
    complete: function(){
     j('input#check_stockist_code_btn').attr('disabled','');
    }
   });
  }
 });
});
</script>";

//back button
$back_url=$list_file;

//format input row
$display_fields=array("name","username","stockist_uid","stockist_code");

foreach($form_fields as $field => $default){
 if(in_array($field, $display_fields)){
  $db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;
  $dbr=explode("#", $vars["dbr"]["users"][$db_fieldname]);
  $readonly=$textarea=false;
  $extra_display='';
  if($field=='stockist_code'){
   $extra_display="<br />\n"." <span id='stockist_code_text'>$stockist_code_text</span> <input type='button' name='check_stockist_code_btn' id='check_stockist_code_btn' value=\"".__("Check Stockist Code")."\" />";
  }else{
   $extra_display='';
   $readonly=true;
  }
  $readonly_str=$readonly? "readonly='readonly'" : "";
  $form_inputfield[$db_fieldname]="
  <tr>
   <td width='$td_width'>".__($dbr[4]).__(":").($dbr[3]=='m'? " ".__("*") : "")."</td>
   <td>".($textarea? "<textarea name='$field' rows='6' $inputbox_style $readonly_str>".$dis[$field]."</textarea>" : "
   <input type='text' name='$field' $inputbox_style value=\"".$dis[$field]."\" $readonly_str />")."$extra_display</td>
  </tr>";
 }
}

$manage_user=($errmsg || $msg? $errmsg.$msg : "").
"<form name='aj_form' method='post' action='$this_file'></form>
<form name='user_form' method='post' action='$this_file?$_SERVER[QUERY_STRING]'>
<input type='hidden' name='__req' value='1' />
<input type='hidden' name='back_url' value=\"$back_url\" />
<table class='amt_table' width='80%'>
 <tr class='amt_header'>
  <td colspan='2'><b>".__("Stockist Information")."</b></td>
 </tr>
 <tr>
  <td width='$td_width'>".__("ID").__(":")."</td>
  <td>$get_s[id]</td>
 </tr>
 $form_inputfield[name]
 $form_inputfield[username]
 $form_inputfield[stockist_uid]
 $form_inputfield[stockist_code]
 <tr>
  <td colspan='2' class='center' style='padding:20px 0 20px 0;'>
   <input type='button' value=\"".__("Back")."\" onclick=\"location='$back_url';\">&nbsp;&nbsp;&nbsp;
   <input type='submit' name='submit_btn' value=\"".($_GET["type"]=="edit"? __("Update Stockist") : __("Add Stockist"))."\" />
  </td>
</table>
</form>
$c_jvscript";

$content="<h2>$page_title</h2>$manage_user";

print format_member_page($content, $this_title, $content_title, $css.$jvscript);
?>